package com.wuwangfu.window.process;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * @Author jcshen
 * @Date 2023-02-24
 * @PackageName:com.wuwangfu.window
 * @ClassName: ProcessTimeSlideWindwoAll
 * @Description:
 * @Version 1.0.0
 *
 *  https://nightlies.apache.org/flink/flink-docs-release-1.14/docs/dev/datastream/operators/windows/#sliding-windows
 * 不分组，按照processTime划分滑动窗口
 */
public class ProcessTimeSlideWindwoAll {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //旧版本需要设置时间类型，新版本默认就是processTime
        //env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);
        DataStreamSource<String> line = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> maped = line.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.valueOf(fields[1]));
            }
        });
        /*旧API*/
        //maped.timeWindowAll(Time.seconds(5),Time.seconds(3)).sum(1).print();
        /*新API*/
        //windowAll 并行度为1
        AllWindowedStream<Tuple2<String, Integer>, TimeWindow> windowed = maped.windowAll(SlidingProcessingTimeWindows.of(Time.seconds(30), Time.seconds(10)));
        windowed.sum(1).print();


        env.execute();
    }
}
